package com.budwk.app.sqfwV2.generator.dayingRoadPdf;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.BaseTemplatePdfGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.SqfwPdfCreateCommonBO;
import com.budwk.app.sqfwV2.component.DayingRoadPdfComponent;
import com.budwk.app.sqfwV2.dto.dto.FireSafetyOnDayingRoadPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.AccommodatePeopleVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.SandwichingVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.template.SmallBusinessPdfVo;
import com.budwk.app.sys.models.Sys_dict;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.PictureUtils;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;

/**
 * 小型生产经营性场所消防安全综合治理记录，版本号1.0
 */

@Slf4j
public class SmallBusinessGenerator extends BaseTemplatePdfGenerator{

    /**
    * 判断使用使用这个generator生成pdf
    *
    * @param pdfDTO 提交了必生成
     *               ○注：除【主要经营范围】的值为：【大型商场、超市、酒店】、
     *               【幼儿园、寄宿制学校、社会福利机构】、【医院、诊所、卫生服务站】、
     *               【劳动密集型企业、多业态混合经营场所】、【其他重点消防安全场所】中任意一项时，不生成该pdf。（2024.3.21补充逻辑）
    * @return 结果
    */
    @Override
    public boolean pdfCreateConditionCheck(SqfwPdfCreateCommonBO pdfDTO) {
        FireSafetyOnDayingRoadPdfDTO roadPdfDTO = DayingRoadPdfComponent.getFireSafetyOnDayingRoadPdfDTO(pdfDTO);
        return !DayingRoadPdfComponent.isKeyLocations(roadPdfDTO);
    }

    @Override
    public String getTemplateName() {
        return "sqfwV2/daYingLu/smallBusinessPremisesSafetyGoverRecord.docx";
    }

    @Override
    public void customerPopularPdfParam(Map<String, Object> paramMap, SqfwPdfCreateCommonBO pdfDTO) {
        // 解析对象
        FireSafetyOnDayingRoadPdfDTO roadPdfDTO = DayingRoadPdfComponent.getFireSafetyOnDayingRoadPdfDTO(paramMap, pdfDTO);
        // 构建模板参数
        SmallBusinessPdfVo pdfVo = buildSmallBusinessPdfVo(paramMap, roadPdfDTO, pdfDTO);
        Map<String, Object> stringObjectMap = CommonComponent.entityToMap(pdfVo);
        paramMap.putAll(stringObjectMap);
        log.info("SmallBusinessGenerator param: {}", JSONObject.toJSONString(paramMap));
    }

    private SmallBusinessPdfVo buildSmallBusinessPdfVo(Map<String, Object> paramMap, FireSafetyOnDayingRoadPdfDTO roadPdfDTO, SqfwPdfCreateCommonBO pdfDTO) {
        SmallBusinessPdfVo pdfVo = new SmallBusinessPdfVo();
        // 1 封装基本参数
        pdfVo.setUnitName(pdfDTO.getBasePdfParamDTO().getUnitName())
                .setInspectionDate(LocalDateTimeUtil.format(roadPdfDTO.getInspectionDate(), DatePattern.NORM_DATE_PATTERN))
                .setCName(StrUtil.formatStr(roadPdfDTO.getPlaceName()))
                .setAddress(StrUtil.formatStr(roadPdfDTO.getAddress()))
                .setOperator(StrUtil.formatStr(roadPdfDTO.getOperator()))
                .setDistrict(StrUtil.formatStr(pdfDTO.getBasePdfParamDTO().getDistrict()))
                .setOperatorPhone(StrUtil.formatStr(roadPdfDTO.getOperatorTelephone()));
        // 主要经营产品
        pdfVo.setMainBCode(StrUtil.formatStr(roadPdfDTO.getMainBusinessScope()));
        // 建筑类型
        pdfVo.setBuildCode(StrUtil.formatStr(roadPdfDTO.getBuildingType()));
        // 是否搭建夹层
        analySandwichingVo(roadPdfDTO.getSandwichConstructionUse(), pdfVo);
        // 是否住人
        accommodatePeople(roadPdfDTO.getAccommodatePeople(), pdfVo);
        // 消防设施情况
        SysDictService dictService = NutzIocUtils.getBean(SysDictService.class);
        fireFacilitiesSituation(roadPdfDTO, pdfVo, dictService);
        // 电气线路情况
        electricalSituation(roadPdfDTO, pdfVo, dictService);
        // 电动自行车使用情况
        electricBicyclesUsage(roadPdfDTO, pdfVo, dictService);
        // 是否使用明火、高温加热、取暖设备等  待开发 暂不确定
        flamesHeatingEquipment(roadPdfDTO, pdfVo);
        // 是否存放易燃易爆
        areFlammable(roadPdfDTO, pdfVo);
        // 宣传教育培训
        safeTraining(roadPdfDTO, pdfVo);
        // 隐患及整改情况
        List<SafeCheckTaskParamDataDTO> otherHiddenDangers = roadPdfDTO.getOtherHiddenDangers();
        if (otherHiddenDangers != null && otherHiddenDangers.size() > 0) {
            SafeCheckTaskParamDataDTO s = otherHiddenDangers.get(otherHiddenDangers.size() - 1);
            pdfVo.setYhs(s.getRectificationMeasure());
        }
        // 签名
        DayingRoadPdfComponent.buildPeersSign(pdfDTO, roadPdfDTO, paramMap);
        return pdfVo;
    }

    // 宣传教育培训
    private void safeTraining(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, SmallBusinessPdfVo pdfVo) {
        pdfVo.setKp(roadPdfDTO.getIsPeriodicalAirAndPersonTrain()).setYs(roadPdfDTO.getPersonnelOneThreeSkills());
    }

    // 是否存放易燃易爆
    private void areFlammable(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, SmallBusinessPdfVo pdfVo) {
        SafeCheckTaskParamDataDTO p = roadPdfDTO.getIsCombustiblEexplosive();
        if (p == null) {
            return;
        }
        String key = p.getKey();
        if (String.valueOf(Boolean.TRUE).equals(key)) {
            pdfVo.setYby(true).setYbs(StrUtil.formatStr(p.getRectificationMeasure()));
            return;
        }
        if (String.valueOf(Boolean.FALSE).equals(key)) {
            pdfVo.setYby(false).setYbs(StrUtil.formatStr(p.getRectificationMeasure()));
            return;
        }
        pdfVo.setYbo(p.getRectificationMeasure());
    }

    // 是否使用明火、高温加热、取暖设备等
    private void flamesHeatingEquipment(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, SmallBusinessPdfVo pdfVo) {
        // 待开发 暂不确定
        SafeCheckTaskParamDataDTO p = roadPdfDTO.getFireHighUsageArea();
        if (p == null) {
            return;
        }
        String key = p.getKey();
        if (StringUtils.isEmpty(key)) {
            return;
        }
        // 1：没有使用  2：夹层   3：其他
        if (DictConstants.FLAMES_HIGH_HEAT_NO.equals(key)) {
            pdfVo.setMhqy(false);
            return;
        }
        if (DictConstants.FLAMES_HIGH_HEAT_SAND.equals(key)) {
            pdfVo.setMhqy(true).setMhqdj(true);
            return;
        }
        if (DictConstants.FLAMES_HIGH_HEAT_OTHER.equals(key)) {
            pdfVo.setMhqy(true).setMhqdo(true).setMhqo(StrUtil.formatStr(p.getRectificationMeasure()));
        }
    }

    // 电动自行车使用情况
    private void electricBicyclesUsage(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, SmallBusinessPdfVo pdfVo, SysDictService dictService) {
        SafeCheckTaskParamDataDTO p = roadPdfDTO.getElectricBicyclesUse();
        if (p == null) {
            return;
        }
        String key = p.getKey();
        // 没有使用电动车充电情况
        if (DictConstants.BICYCLES_NO.equals(key)) {
            pdfVo.setDzy(false);
            return;
        }
        // 2 使用电动车充电
        if (DictConstants.BICYCLES_INDOOR.equals(key)) {
            pdfVo.setDzy(true).setSn(true);
            return;
        }
        if (DictConstants.BICYCLES_OUTDOOR.equals(key)) {
            pdfVo.setDzy(true).setSw(true);
            return;
        }
        if (DictConstants.BICYCLES_FLYWIRE.equals(key)) {
            pdfVo.setDzy(true).setFx(true);
            return;
        }
        // 3 其他
        if (DictConstants.BICYCLES_OTHER.equals(key)) {
            pdfVo.setDdo(StrUtil.formatStr(p.getRectificationMeasure()));
        }
    }

    private void electricalSituation(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, SmallBusinessPdfVo pdfVo, SysDictService dictService) {
        SafeCheckTaskParamDataDTO p = roadPdfDTO.getElectricalCircuitSituation();
        if (p == null) {
            return;
        }
        String key = p.getKey();
        // 1 合格
        if (DictConstants.ELECTRICAL_CIRCUIT_QUALIFIED.equals(key)) {
            pdfVo.setDqy(true);
            return;
        }
        // 2 不合格
        if (DictConstants.ELECTRICAL_CIRCUIT_RANDOMLY.equals(key)) {
            pdfVo.setDqy(false).setLj(true);
            return;
        }
        if (DictConstants.ELECTRICAL_CIRCUIT_PRODUCTS.equals(key)) {
            pdfVo.setDqy(false).setJm(true);
            return;
        }
        if (DictConstants.ELECTRICAL_CIRCUIT_CONSUMPTION.equals(key)) {
            pdfVo.setDqy(false).setCf(true);
            return;
        }
        // 3 其他
        if (DictConstants.ELECTRICAL_CIRCUIT_OTHER.equals(key)) {
            pdfVo.setDqo(StrUtil.formatStr(p.getRectificationMeasure()));
        }
    }

    private void fireFacilitiesSituation(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, SmallBusinessPdfVo pdfVo, SysDictService dictService) {
        // 1 火灾自动报警系统
        SafeCheckTaskParamDataDTO p1 = roadPdfDTO.getFireHouseAlarmSystem();
        if (p1 != null) {
            pdfVo.setFby(String.valueOf(Boolean.TRUE).equals(p1.getKey())).setFbo(StrUtil.formatStr(p1.getRectificationMeasure()));
        }
        // 2 自动喷水灭火系统
        SafeCheckTaskParamDataDTO p2 = roadPdfDTO.getAutomaticSprinklerSystem();
        if (p2 != null) {
            pdfVo.setMfy(String.valueOf(Boolean.TRUE).equals(p2.getKey())).setMfo(StrUtil.formatStr(p2.getRectificationMeasure()));
        }
        // 3 室内消火栓
        SafeCheckTaskParamDataDTO p3 = roadPdfDTO.getIndoorFireHydrant();
        if (p3 != null) {
            pdfVo.setXhy(String.valueOf(Boolean.TRUE).equals(p3.getKey())).setXho(StrUtil.formatStr(p3.getRectificationMeasure()));
        }
        // 4 灭火器
        SafeCheckTaskParamDataDTO pfen = roadPdfDTO.getWhetherEquippedFire();
        if (pfen != null) {
            if (pfen.getKey().equals("true")) {
                String remark = pfen.getRectificationMeasure();
                if (StringUtils.isNotEmpty(remark)) {
                    Sys_dict sysDict = dictService.fetch(Cnd.where(Sys_dict::getCode, "=", remark));
                    pdfVo.setMhy(true).setMhyn(sysDict.getName());
                }
            }
        }
        // 5 消防设施的其他问题
        pdfVo.setMho(roadPdfDTO.getFireOtherIssues() != null ? StrUtil.formatStr(roadPdfDTO.getFireOtherIssues().getRectificationMeasure()) : "");
    }


    // 是否住人
    private void accommodatePeople(AccommodatePeopleVo accommodatePeople, SmallBusinessPdfVo pdfVo) {
        if (accommodatePeople == null) {
            return;
        }
        // 住人形式
        if (StringUtils.isNotEmpty(accommodatePeople.getResidentialType())) {
            if (!accommodatePeople.getResidentialType().equals(DictConstants.RESIDENTS_FORM_STAY_NOPERSON)) {
                pdfVo.setPer(true);
            }
        }
        pdfVo.setPNum(accommodatePeople.getResidentialNum())
                .setJzNum(accommodatePeople.getResidentialLayerNum());
        // 住宿区域是否有安全出口
        if (StringUtils.isNotEmpty(accommodatePeople.getSafeExport())) {
            pdfVo.setZsct(DictConstants.RESIDENTS_SAFE_REQUIREMENT.equals(accommodatePeople.getSafeExport()))
                    .setSetJT(DictConstants.RESIDENTS_SAFE_DOORS_FENCES.equals(accommodatePeople.getSafeExport()))
                    .setZsn(DictConstants.RESIDENTS_SAFE_NO.equals(accommodatePeople.getSafeExport()));
            pdfVo.setZsy(pdfVo.isZsct() || pdfVo.isSetJT());
            pdfVo.setZs(pdfVo.isZsct() || pdfVo.isSetJT());
        }
        // 住宿区域是否有逃生外窗
        if (StringUtils.isNotEmpty(accommodatePeople.getResidentsEscapeWindow())) {
            pdfVo.setZswct(DictConstants.RESIDENTS_ESCAPE_REQUIREMENT.equals(accommodatePeople.getResidentsEscapeWindow()))
                    .setSetfd(DictConstants.RESIDENTS_ESCAPE_SET_WINDOWS.equals(accommodatePeople.getResidentsEscapeWindow()))
                    .setZswn(DictConstants.RESIDENTS_ESCAPE_NO.equals(accommodatePeople.getResidentsEscapeWindow()))
                    .setYngd(DictConstants.RESIDENTS_ESCAPE_YES.equals(accommodatePeople.getResidentsEscapeWindow()));
        }
        pdfVo.setPform(StrUtil.formatStr(accommodatePeople.getResidentialType()));
        // 经营与住区域是否有防火分隔
        SafeCheckTaskParamDataDTO s = accommodatePeople.getResidentialAreas();
        if (s != null) {
            pdfVo.setJbusfy(String.valueOf(Boolean.TRUE).equals(s.getKey()))
                    .setJbusfct(String.valueOf(Boolean.TRUE).equals(s.getKey()) ? s.getRectificationMeasure() : StringUtils.EMPTY)
                    .setJbusfcnct(String.valueOf(Boolean.FALSE).equals(s.getKey()) ? s.getRectificationMeasure() : StringUtils.EMPTY);
        }
        // 其他
        pdfVo.setOther(StrUtil.formatStr(accommodatePeople.getOther()));
    }

    // 夹层搭建使用
    private void analySandwichingVo(SandwichingVo sandwichingVo, SmallBusinessPdfVo pdfVo) {
        if (sandwichingVo == null) {
            return;
        }
        pdfVo.setJcIsUse(false);
        if (StringUtils.isNotEmpty(sandwichingVo.getDictId())) {
            if (DictConstants.SANDWICH_USE_STOREROOM.equals(sandwichingVo.getDictId())) {
                pdfVo.setKf(true).setJcIsUse(true);
            }
            if (DictConstants.SANDWICH_USE_LIVE.equals(sandwichingVo.getDictId())) {
                pdfVo.setJz(true).setJcIsUse(true);
            }
            if (DictConstants.SANDWICH_USE_JY.equals(sandwichingVo.getDictId())) {
                pdfVo.setJy(true).setJcIsUse(true);
            }
            if (DictConstants.SANDWICH_USE_BG.equals(sandwichingVo.getDictId())) {
                pdfVo.setBg(true).setJcIsUse(true);
            }
        }
        // 搭建层数
        pdfVo.setJcNum(sandwichingVo.getDjJcNum());
        // 夹层楼板
        SafeCheckTaskParamDataDTO p = sandwichingVo.getMezzaninFfloorSlab();
        pdfVo.setJcFloor(p != null ? p.getKey() : "");
        // 楼梯建筑材料
        SafeCheckTaskParamDataDTO pm = sandwichingVo.getStaircaseBuildingMaterials();
        if (pm != null && StringUtils.isNotEmpty(pm.getKey())) {
            if (DictConstants.STAIRCASE_BUILD_MATERIALS_COMBUSTIBLE.equals(pm.getKey())) {
                pdfVo.setFire(true).setFireS(pm.getRectificationMeasure());
            }
            if (DictConstants.STAIRCASE_BUILD_MATERIALS_INCOMBUSTIBLE.equals(pm.getKey())) {
                pdfVo.setNoFire(true).setNoFireS(pm.getRectificationMeasure());
            }
        }
    }

    @Override
    public ByteArrayOutputStream generatePDFAfter(XWPFTemplate xwpfTemplate, Sqfw_formSummary_new formSummary) {
        if (!DayingRoadPdfComponent.isDayYingStreet(formSummary.getUnitName())) {
            return null;
        }
        ByteArrayOutputStream wordOutPutStream = new ByteArrayOutputStream();
        if (xwpfTemplate != null) {
            NiceXWPFDocument xwpfDocument = xwpfTemplate.getXWPFDocument();
            try {
                xwpfDocument = PictureUtils.localImageSeal(xwpfDocument, "被检查场所名称", PictureUtils.getLocalImagePath(formSummary.getUnitName()),
                        40, -15, 115);

                xwpfDocument.write(wordOutPutStream);
                return wordOutPutStream;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                PictureUtils.close(xwpfTemplate, xwpfDocument);
            }
        }
        return wordOutPutStream;
    }
}
